﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Base;

namespace HRM
{
    public partial class FormOvertimeRegistration : FormBaseDataGrid
    {
        private Ctrl_General mCtrlGeneral;
        private DataSet mdsOTRegiste;
        private SqlDataAdapter mdaOTRegisteUpdate;

        public FormOvertimeRegistration()
        {
            InitializeComponent();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        #region Override LoadMasterData
        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                cboYear.Text = DateTime.Now.Year.ToString();
                cboMonth.Text = (DateTime.Now.Month.ToString().Length == 1 ? "0" + DateTime.Now.Month.ToString() : DateTime.Now.Month.ToString());
                LoadData();
                btnImport.Enabled = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load Overtime Registration Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        #endregion

        #region LoadData method
        private void LoadData()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondiction = " Where OTR.Years = " + cboYear.Text.Trim() + " and OTR.Months = " + cboMonth.Text.Trim() + " Order By OTR.Begin_Date ";
                string lCondiction1 = " Years = " + cboYear.Text.Trim() + " and Months = " + cboMonth.Text.Trim() + " Order By Begin_Date ";

                string ls_SQL = "Select OTR.ID_Emp, PF.Emp_NameVN, OTR.Years, OTR.Months, OTR.Begin_Date, OTR.End_Date, OTR.Hrs, OTR.HrsApr, "
                    + " OTR.ID_OvertimeType, OTT.OvertimeType_Name, OTR.Note, "
                    + "OTR.CreatedUser, OTR.UpdatedUser, OTR.CreatedDate, OTR.UpdatedDate "
                    + "From HRM_PersonnelOvertimeRegist OTR inner join HRM_PersonalProfile PF on OTR.ID_Emp = PF.ID_Emp "
                    + " left outer join HRM_OvertimeType OTT on OTR.ID_OvertimeType = OTT.ID_OvertimeType "
                    + lCondiction;

                mdsOTRegiste = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelOvertimeRegist");
                mCtrlGeneral.GetDataWithCondition(out mdaOTRegisteUpdate, "HRM_PersonnelOvertimeRegist", lCondiction1);

                if (mdsOTRegiste == null) return;
                mdbg_dataGrid.DataSource = mdsOTRegiste;
                mdbg_dataGrid.DataMember = "HRM_PersonnelOvertimeRegist";


                mRowManager = (CurrencyManager)mdbg_dataGrid.BindingContext[mdsOTRegiste, "HRM_PersonnelOvertimeRegist"];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);

                base.LoadMasterData();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Overtime Registration Form'. Error: '" + ex.Message + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Ctrl_LOG.Print("Overtime Registration Form", "LoadData() method", "Error: " + ex.Message);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        public override void save()
        {
            try
            {
                if (mdsOTRegiste == null) return;
                mRowManager.EndCurrentEdit();
                if (!mdsOTRegiste.HasChanges())
                {
                    base.save();
                    return;
                }
                DataSet ldsHasChanged = mdsOTRegiste.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    if (dr.RowState == DataRowState.Added)
                    {
                        dr["CreatedDate"] = DateTime.Now;
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["Years"] = cboYear.Text.Trim();
                        dr["Months"] = cboMonth.Text;
                        dr["HrsApr"] = dr["Hrs"];
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["HrsApr"] = dr["Hrs"];
                        dr["UpdatedDate"] = DateTime.Now;
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaOTRegisteUpdate, ldsHasChanged, "HRM_PersonnelOvertimeRegist", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsOTRegiste.AcceptChanges();
                    int li_pos = 0;
                    if (GetCurrentAction() == MODES.MODIFY) li_pos = mRowManager.Position;
                    LoadData();
                    if (li_pos > 0) mRowManager.Position = li_pos;
                    base.save();
                    btnBrowse.Enabled = true;
                    btnImport.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Cannot save'. Error: '" + ls_Error + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public override void cancel()
        {
            mdbg_dataGrid.Focus();
            if (mdsOTRegiste == null) return;
            mRowManager.EndCurrentEdit();
            mdsOTRegiste.RejectChanges();
            base.cancel();
            btnBrowse.Enabled = true;
            btnImport.Enabled = false;
        }

        public override void add()
        {
            mdbg_dataGrid.Focus();
            base.add();
            btnBrowse.Enabled = false;
            btnImport.Enabled = false;
        }

        public override void modify()
        {
            base.modify();
            btnBrowse.Enabled = false;
            btnImport.Enabled = false;
        }

        public override void delete()
        {
            base.delete();
            if (!mb_AcceptDelete) return;
            DataSet ldsDelete = (DataSet)mdbg_dataGrid.DataSource;
            DataRow ldrDelete = ldsDelete.Tables[0].Rows[mRowManager.Position];
            ldrDelete.Delete();
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaOTRegisteUpdate, ldsDelete, "HRM_PersonnelOvertimeRegist", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete'. Error: '" + lsReturnMessage + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
            }
        }

        protected override void mdbg_dataGrid_KeyUp(object sender, KeyEventArgs e)
        {
            if (GetCurrentAction() == MODES.FULL || GetCurrentAction() == MODES.VOID) return;
            if (e.KeyCode != Keys.F9) return;
            OpenSelection(mdbg_dataGrid.Columns[mdbg_dataGrid.CurrentCell.ColumnIndex].Name);
        }

        #region Open selection
        public override void OpenSelection(string as_SelectioField)
        {
            SelectionParam lstr_param = new SelectionParam();
            lstr_param.ms_SelectionField = as_SelectioField;
            FormSelection lfrmSelect = new FormSelection();
            lfrmSelect.mfrmParentForm = this;
            lfrmSelect.Owner = mMainForm;

            switch (as_SelectioField)
            {
                case "ID_Emp":
                    lstr_param.ms_SelectionName = "Personnel Profile";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        string[] astrID = lfrmSelect.GetParam().msa_ReturnValues[0].Split(',');
                        string[] astrName = lfrmSelect.GetParam().msa_ReturnValues[1].Split(',');
                        if (astrID.Length == 1)
                        {
                            mdbg_dataGrid["ID_Emp", mdbg_dataGrid.CurrentCell.RowIndex].Value = lfrmSelect.GetParam().msa_ReturnValues[0];
                            mdbg_dataGrid["Emp_NameVN", mdbg_dataGrid.CurrentCell.RowIndex].Value = lfrmSelect.GetParam().msa_ReturnValues[1];
                            mdbg_dataGrid["Begin_Date", mdbg_dataGrid.CurrentCell.RowIndex].Value = DateTime.Now;
                            mdbg_dataGrid["End_Date", mdbg_dataGrid.CurrentCell.RowIndex].Value = DateTime.Now;
                            mdbg_dataGrid["Hrs", mdbg_dataGrid.CurrentCell.RowIndex].Value = 8;
                            mdbg_dataGrid["HrsApr", mdbg_dataGrid.CurrentCell.RowIndex].Value = 8;
                        }
                        else
                        {   // Assign first value for current row
                            mdbg_dataGrid["ID_Emp", mdbg_dataGrid.CurrentCell.RowIndex].Value = astrID[0];
                            mdbg_dataGrid["Emp_NameVN", mdbg_dataGrid.CurrentCell.RowIndex].Value = astrName[0];
                            mdbg_dataGrid["Begin_Date", mdbg_dataGrid.CurrentCell.RowIndex].Value = DateTime.Now;
                            mdbg_dataGrid["End_Date", mdbg_dataGrid.CurrentCell.RowIndex].Value = DateTime.Now;
                            mdbg_dataGrid["Hrs", mdbg_dataGrid.CurrentCell.RowIndex].Value = 8;
                            // Assign next value for new row
                            DataRow dr;
                            for (int i = 1; i < astrID.Length; i++)
                            {
                                dr = mdsOTRegiste.Tables[0].NewRow();
                                dr["ID_Emp"] = astrID[i];
                                dr["Emp_NameVN"] = astrName[i];
                                dr["Begin_Date"] = DateTime.Now;
                                dr["End_Date"] = DateTime.Now;
                                dr["Hrs"] = 8;
                                dr["HrsApr"] = 8;
                                mdsOTRegiste.Tables[0].Rows.Add(dr);
                            }
                        }
                    } break;

                case "ID_OvertimeType":
                    lstr_param.ms_SelectionName = "Overtime Type";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        mdbg_dataGrid["ID_OvertimeType", mdbg_dataGrid.CurrentCell.RowIndex].Value = lfrmSelect.GetParam().msa_ReturnValues[0];
                        mdbg_dataGrid["OvertimeType_Name", mdbg_dataGrid.CurrentCell.RowIndex].Value = lfrmSelect.GetParam().msa_ReturnValues[1];
                    } break;

            }
        }
        #endregion

        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            string lFilePath = "";
            if (!mCtrlGeneral.GetPathOpenFileDlg(out lFilePath))
                MessageBox.Show("Cannot get 'Overtime Registration' file path. Error message: '" + lFilePath + "'", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                lblFilePath.Text = lFilePath;
                btnImport.Enabled = true;
            }
        }

        private void btnTemplate_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                CreateExcelDoc excell_app = new CreateExcelDoc();
                //creates text header for excel file
                string lsMsg = excell_app.ExportDGV2XLSX(1, 1, mdbg_dataGrid);
                if (!lsMsg.Equals("")) MessageBox.Show("Cannot get 'Overtime Registration' template. Error message: " + lsMsg, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot get 'Overtime Registration' template. Error message: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                CreateExcelDoc excell_app = new CreateExcelDoc();
                base.add();
                // build defalt values
                Dictionary<string, object> dict = new Dictionary<string, object>();
                dict.Add("Years", cboYear.Text.Trim());
                dict.Add("Months", cboMonth.Text);
                dict.Add("HrsApr", 8);
                dict.Add("CreatedUser", mMainForm.ms_UserID);
                dict.Add("CreatedDate", DateTime.Now);
                dict.Add("UpdatedUser", null);
                dict.Add("UpdatedDate", DateTime.MaxValue);
                // Import data from excel file to grid
                excell_app.ImportXLSX2DGV(lblFilePath.Text, mdbg_dataGrid, dict);
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot import Overtime Registration from excel file. Error message: " + ex.Message, ConstantKeys.Title);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btnFilter_Click(object sender, EventArgs e)
        {
            mdbg_dataGrid.ResumeLayout(true);
            LoadData();
        }
    }
}
